import { logout, statistics, userInfo } from "@/api/user";


const state = {
  userInfo: '',
  userToken: localStorage.getItem('USER_TOKEN'), // 登陆token
  userLanguage: {
    text: 'English',
    code: 'en_US', // 用户语言
  },
  userCurrency: {
    text: '$', // 符号
    currencySymbol: '$',
    code: 'USD', // 名称
  },
  userReminder: '', // 用户商品数量圆点提醒
  cartNum: 0, // 购物车数量
  doubleCartNum: 0,
  cartBill: {
    cartEvent: null,
    status: false
  }
};
const mutations = {
  setCartEvent(state, info) {
    state.cartBill.cartEvent = info.el;
    state.cartBill.status = !state.cartBill.status;
  },
  removeCartNum(state, num) {
    // 删除购物车的数量
    state.cartNum = state.cartNum - num;
  },
  setCartNum(state, num) {
    state.cartNum = num; // 设置购物车数量
  },
  setDoubleCartNum(state, num) {
    state.doubleCartNum = num; // 双11购物车数量
  },
  setUserCurrency(state, currency) {
    // 设置币种
    if (currency.code) {
      state.userCurrency = currency;
    }
  },
  setUserLanguage(state, lang) {
    // 设置语言啊
    if (lang.code) {
      state.userLanguage = lang;
    }
  },
  setUserInfo(state, data) {
    // 设置用户信息
    state.userInfo = data;
  },
  setUserToken(state, userTokenInfo) {
    // 设置用户的token
    state.userToken = userTokenInfo;
  },
  setUserFee(state, userTokenInfo) {
    state.userFeeInfo = userTokenInfo;
  },
  setUserReminder(state, data) {
    state.userReminder = data;
  },
  resetUserInfo(state) {
    // 重置用户的信息
    state.userInfo = '';
    state.userToken = '';
    localStorage.removeItem('USER_TOKEN');
  }
};
const actions = {
  getStatistics({ commit }) {
    // 获取用户的状态
    statistics().then((res) => {
      if (res.result.shopCartQuantity) {
        commit('setCartNum', res.result.shopCartQuantity)
      }
      commit('setUserReminder', res.result);
    });
  },
  getUserInfo({ commit, dispatch }) {
    // 获取用户信息
    return new Promise((resolve, reject) => {
      userInfo().then((res) => {
        commit('setUserInfo', res.result);
        dispatch('getStatistics');
        if (window.ssq) {
          ssq.push('clearUser');
          ssq.push('setLoginInfo', {
            user_id: res.result.id, // 加密后的用户id, 必填！
            user_name: res.result.userName, // 对应用户名
            language: 'en-US', // 对应用户语言
            email: res.result.email,
          });
        }
        resolve(res.result);
      }).catch((error) => {
        reject(error)
      })
    })
  }
};


export default {
  state,
  actions,
  mutations
}
